package network.client;

import network.Message;
import network.SocketConnection;

import java.io.Closeable;
import java.io.IOException;
import java.net.Socket;

public class ClientStub implements Closeable{
    private SocketConnection connection;
    private String nickName = "Anonymous";
    private String room = "default";

    public String getRoom() {
        return room;
    }

    public void setRoom(String room) {
        this.room = room;
    }

    public void setNickName(String nickName) {
        this.nickName = nickName;
    }

    public String getNickName() {
        return nickName;
    }

    public void connect(String host, int port) throws ChatException {
        try {
            connection = new SocketConnection(new Socket(host, port));
        } catch (IOException e) {
            throw new ChatException(e);
        }
    }

    public Message processServerRequest() throws ChatException, ClassNotFoundException {
        try {
            Message reply = (Message)connection.read();
            if( reply.isSenderAdmin() && reply.isSuccess()) {
                if (reply.isValidCHID()) {
                    setNickName(reply.getRecipient());
                } else if (reply.isValidCHROOM()) {
                    setRoom(reply.getRoom());
                }
            }

            return reply;
        } catch (IOException e) {
            throw new ChatException(e);
        }
    }

    public boolean processClientRequest(String request) throws ChatException {
        try {
            Message outcomingMessage = new Message();
            outcomingMessage.setSender(nickName);
            outcomingMessage.setRoom(room);
            if (outcomingMessage.parseRequest(request)) {
                if (outcomingMessage.isValid()) {
                    connection.write(outcomingMessage);
                    return true;
                }
            }
            return false;
        } catch (IOException e) {
            throw new ChatException(e);
        }
    }

    @Override
    public void close() throws IOException {
        connection.close();
    }
}